<template>
  <section class="todoapp">
    <!-- 使用 -->
    <TodoHeader @addTask="hAddTask" />
    <!-- 在父组件中传递给子组件 -->
    <TodoMain 
    @chengeAll="hChangeAll"
    @changeDone="hChangeDone" 
    @delTask="hDelTask" 
    :list="showList" />

    <TodoFooter

      @changeType="hChangeType"
      @clearDone="hClearDone"
      :list="showList"
    />
  </section>
</template>

<script>
// 引入三个组件
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
import TodoFooter from "./components/TodoFooter.vue";
export default {
  // 注册
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      // list: [
      //   { id: 1, name: "吃饭", isDone: true },
      //   { id: 2, name: "睡觉", isDone: false },
      //   { id: 3, name: "打豆豆", isDone: true },
      // ],
      list:JSON.parse(localStorage.getItem('list')||'[]'),
      type:'all'
    };
  },
  methods: {
    hDelTask(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    hChangeDone(id) {
      const obj = this.list.find((item) => item.id === id);
      obj.isDone = !obj.isDone;
    },
    hAddTask(taskname) {
      this.list.push({
        name: taskname,
        id: Date.now(),
        isDone: false,
      });
    },
    hClearDone() {
      this.list = this.list.filter((item) => !item.isDone);
    },
    hChangeType(type) {
      this.type = type;
    },
    hChangeAll(val){
      this.list.forEach(item=>item.isDone= val)
    }
  },
  computed: {
    showList() {
      //在计算属性中,根据传过来的type来决定返回什么数组
      if (this.type === 'all') {
        return this.list;
      } else if (this.type === 'no') {
        //筛选所有未完成的任务列表返回
        return this.list.filter(item => !item.isDone);
      } else if (this.type === 'yes') {
        //筛选所有已完成的裂任务列表返回
        return this.list.filter(item => item.isDone);
      }
    }
  },
  watch:{
    list:{
      deep:true,
      handler(){
     localStorage.setItem('list', JSON.stringify(this.list))
      }
    }
  }
}
</script>

<style></style>
